package com.example.mydy.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.util.Log;

import com.example.mydy.model.UserData;
import com.example.mydy.model.UserInfo;
import com.example.mydy.model.WithdrawalRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 提现服务类，处理提现请求的CRUD操作和业务逻辑
 */
public class WithdrawalService {
    private static final String TAG = "WithdrawalService";
    private static final String PREFS_NAME = "WithdrawalPrefs";
    private static final String KEY_WITHDRAWALS = "withdrawals";

    private SharedPreferences prefs;
    private List<WithdrawalRequest> withdrawalRequests;
    private Gson gson;
    private static WithdrawalService instance;

    public interface WithdrawalCallback {
        void onSuccess();
        void onFailure(String message);
    }

    public interface WithdrawalListCallback {
        void onSuccess(List<WithdrawalRequest> withdrawals);
        void onFailure(String message);
    }

    private WithdrawalService(Context context) {
        prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        gson = new Gson();
        loadWithdrawals();
    }

    public static synchronized WithdrawalService getInstance(Context context) {
        if (instance == null) {
            instance = new WithdrawalService(context.getApplicationContext());
        }
        return instance;
    }

    private void loadWithdrawals() {
        String json = prefs.getString(KEY_WITHDRAWALS, "");
        if (json.isEmpty()) {
            withdrawalRequests = new ArrayList<>();
        } else {
            Type type = new TypeToken<List<WithdrawalRequest>>() {}.getType();
            withdrawalRequests = gson.fromJson(json, type);
        }
    }

    private void saveWithdrawals() {
        String json = gson.toJson(withdrawalRequests);
        prefs.edit().putString(KEY_WITHDRAWALS, json).apply();
    }

    /**
     * 获取所有提现请求
     */
    public void getAllWithdrawals(WithdrawalListCallback callback) {
        new Handler().postDelayed(() -> {
            callback.onSuccess(new ArrayList<>(withdrawalRequests));
        }, 300); // 模拟网络延迟
    }

    /**
     * 按状态筛选提现请求
     */
    public void getWithdrawalsByStatus(String status, WithdrawalListCallback callback) {
        new Handler().postDelayed(() -> {
            List<WithdrawalRequest> filtered = new ArrayList<>();
            for (WithdrawalRequest request : withdrawalRequests) {
                if (status == null || status.isEmpty() || status.equals("ALL") || status.equals(request.getStatus())) {
                    filtered.add(request);
                }
            }
            callback.onSuccess(filtered);
        }, 300); // 模拟网络延迟
    }

    /**
     * 批准提现请求
     * @param request 要批准的提现请求
     * @param remark 备注信息
     * @param callback 回调
     */
    public void approveWithdrawal(WithdrawalRequest request, String remark, WithdrawalCallback callback) {
        // 获取用户信息
        MockDataManager mockDataManager = MockDataManager.getInstance();
        UserInfo user = mockDataManager.getUserById(request.getUserId());
        
        if (user == null) {
            callback.onFailure("找不到用户信息");
            return;
        }
        
        // 检查用户余额是否足够
        double userBalance;
        try {
            userBalance = Double.parseDouble(user.getBalance());
        } catch (NumberFormatException e) {
            userBalance = 0;
        }
        
        if (userBalance < request.getAmount()) {
            callback.onFailure("用户余额不足，无法进行提现");
            return;
        }
        
        // 更新用户余额
        double newBalance = userBalance - request.getAmount();
        user.setBalance(String.valueOf(newBalance));
        mockDataManager.updateUser(user);
        
        // 更新提现请求状态
        for (int i = 0; i < withdrawalRequests.size(); i++) {
            WithdrawalRequest existingRequest = withdrawalRequests.get(i);
            if (existingRequest.getId() == request.getId()) {
                existingRequest.setStatus(WithdrawalRequest.STATUS_APPROVED);
                existingRequest.setProcessTime(new Date());
                existingRequest.setRemark(remark);
                saveWithdrawals();
                break;
            }
        }
        
        // 模拟网络延迟
        new Handler().postDelayed(() -> {
            callback.onSuccess();
        }, 1000);
    }

    /**
     * 拒绝提现请求
     * @param request 要拒绝的提现请求
     * @param remark 拒绝原因
     * @param callback 回调
     */
    public void rejectWithdrawal(WithdrawalRequest request, String remark, WithdrawalCallback callback) {
        // 更新提现请求状态
        for (int i = 0; i < withdrawalRequests.size(); i++) {
            WithdrawalRequest existingRequest = withdrawalRequests.get(i);
            if (existingRequest.getId() == request.getId()) {
                existingRequest.setStatus(WithdrawalRequest.STATUS_REJECTED);
                existingRequest.setProcessTime(new Date());
                existingRequest.setRemark(remark);
                saveWithdrawals();
                break;
            }
        }
        
        // 模拟网络延迟
        new Handler().postDelayed(() -> {
            callback.onSuccess();
        }, 1000);
    }

    /**
     * 用户申请提现
     * @param request 提现请求
     * @param callback 回调
     */
    public void requestWithdrawal(WithdrawalRequest request, WithdrawalCallback callback) {
        // 获取用户信息
        MockDataManager mockDataManager = MockDataManager.getInstance();
        UserInfo user = mockDataManager.getUserById(request.getUserId());
        
        if (user == null) {
            callback.onFailure("找不到用户信息");
            return;
        }
        
        // 检查用户余额是否足够
        double userBalance;
        try {
            userBalance = Double.parseDouble(user.getBalance());
        } catch (NumberFormatException e) {
            userBalance = 0;
        }
        
        if (userBalance < request.getAmount()) {
            callback.onFailure("余额不足，无法申请提现");
            return;
        }
        
        // 生成唯一ID
        int newId = 1;
        if (!withdrawalRequests.isEmpty()) {
            for (WithdrawalRequest existingRequest : withdrawalRequests) {
                if (existingRequest.getId() >= newId) {
                    newId = existingRequest.getId() + 1;
                }
            }
        }
        request.setId(newId);
        
        // 设置初始状态和时间
        request.setStatus(WithdrawalRequest.STATUS_PENDING);
        if (request.getRequestTime() == null) {
            request.setRequestTime(new Date());
        }
        
        // 添加到列表并保存
        withdrawalRequests.add(request);
        saveWithdrawals();
        
        // 模拟网络延迟
        new Handler().postDelayed(() -> {
            callback.onSuccess();
        }, 1000);
    }

    /**
     * 添加模拟数据
     */
    public void addMockData() {
        if (!withdrawalRequests.isEmpty()) {
            return; // 已有数据，不再添加
        }
        
        // 修改从UserData到UserInfo的转换
        List<UserData> userDataList = MockDataManager.getInstance().getAllUsers();
        if (userDataList == null || userDataList.isEmpty()) {
            return;
        }
        
        // 将UserData转换为UserInfo
        List<UserInfo> users = new ArrayList<>();
        for (UserData userData : userDataList) {
            UserInfo userInfo = new UserInfo();
            userInfo.setId(userData.getId());
            userInfo.setUsername(userData.getUsername());
            userInfo.setNickname(userData.getNickname());
            userInfo.setPhone(userData.getPhone());
            userInfo.setBalance(userData.getBalance());
            userInfo.setPoints(userData.getPoints());
            userInfo.setLevel(userData.getLevel());
            userInfo.setStatus(userData.getStatus());
            userInfo.setCreatedAt(userData.getCreatedAt());
            users.add(userInfo);
        }
        
        // 添加一些模拟的提现请求
        Date now = new Date();
        long oneDay = 24 * 60 * 60 * 1000;
        
        for (int i = 0; i < Math.min(users.size(), 5); i++) {
            UserInfo user = users.get(i);
            
            WithdrawalRequest pending = new WithdrawalRequest(
                i + 1,
                user.getId(),
                user.getUsername(),
                user.getNickname(),
                "张" + (i + 1),
                user.getPhone(),
                50.0 + (i * 10),
                WithdrawalRequest.STATUS_PENDING,
                new Date(now.getTime() - (i * oneDay))
            );
            withdrawalRequests.add(pending);
            
            if (i < 2) {
                WithdrawalRequest approved = new WithdrawalRequest(
                    users.size() + i + 1,
                    user.getId(),
                    user.getUsername(),
                    user.getNickname(),
                    "张" + (i + 1),
                    user.getPhone(),
                    30.0 + (i * 5),
                    WithdrawalRequest.STATUS_APPROVED,
                    new Date(now.getTime() - ((i + 5) * oneDay))
                );
                approved.setProcessTime(new Date(now.getTime() - ((i + 4) * oneDay)));
                approved.setRemark("已处理");
                withdrawalRequests.add(approved);
                
                WithdrawalRequest rejected = new WithdrawalRequest(
                    users.size() * 2 + i + 1,
                    user.getId(),
                    user.getUsername(),
                    user.getNickname(),
                    "张" + (i + 1),
                    user.getPhone(),
                    100.0 + (i * 20),
                    WithdrawalRequest.STATUS_REJECTED,
                    new Date(now.getTime() - ((i + 10) * oneDay))
                );
                rejected.setProcessTime(new Date(now.getTime() - ((i + 9) * oneDay)));
                rejected.setRemark("金额异常，已拒绝");
                withdrawalRequests.add(rejected);
            }
        }
        
        saveWithdrawals();
        Log.d(TAG, "添加了 " + withdrawalRequests.size() + " 条模拟提现数据");
    }
} 